<?php
/**
 * Created by PhpStorm.
 * User: xudongsheng
 * Date: 2017/9/21
 * Time: 上午8:49
 */

namespace app\admin\controller;


use app\admin\model\AdminNav;
use app\admin\model\AuthRule;
use app\admin\model\Config;
use Category\Category;
use think\Request;

class Setting extends Common
{
    /** 配置 表单 列表
     * @param Request $request
     * @return mixed
     */
    public function lists(Request $request){
      $request->isPost() AND $this->updateAll();
      $this->assign('config',Config::showConfig());
      return $this->fetch();
    }

    /**
     *  表单 更新
     */
    protected function updateAll(){
        //处理数据
        $config =   input('post.config/a');
        foreach ($config as $k=>$v){
            if (is_array($v)){
                $v  = implode(',',$v);
            }
            Config::update(['value'=>$v],['mark'=>$k]);
        }
        $this->success('已更新！',url('Setting/lists'));
    }

    /** 配置 列表
     * @param null $groups
     * @return mixed
     */
    public function configLists($groups = NULL){
        $this->assign('lists',Config::configList($groups));
        $this->assign('groups',Config::$groups);
        return $this->fetch();
    }

    /** 编辑 配置
     * @param Request $request
     * @param $config_id
     * @return mixed
     */
    public function editConfig(Request $request,$config_id){
        ($config = Config::get($config_id)) OR $this->error('此配置不存在！');
        $request->isPost() AND $this->updateConfig($config);
        $form_view  =   !$config->form_view?:unserialize($config->form_view);
        $this->assign('element',isset($form_view['element'])?$form_view['element']:'select');
        $this->assign('value',isset($form_view['value'])?$form_view['value']:'');
        $this->assign('config',$config);
        $this->assign('groups',Config::$groups);
        $this->assign('types',Config::$types);
        return $this->fetch();
    }

    /**  编辑配置 并 更新
     * @param $config
     */
    private function updateConfig($config){
        // 表单验证

        $data   =   input('post.');
        // 检测 重复值
        if (!empty($data['form_view']['value']) AND $this->checkUnique($data['form_view']['value'])){
            $this->error('" 表单选项 " 填写的多个选项的值不能有重复！');
        }
        $data['form_view']  =   empty($data['form_view']['value'])?'':serialize($data['form_view']);
        if ($config->isUpdate()->allowField(true)->save($data)){
             $this->success('配置'.$config->name.'更新成功！',url('Setting/configLists'));
        }
        $this->error('配置'.$config->name.'更新失败！');

    }

    /** 新增配置
     * @param Request $request
     * @return mixed
     */
    public function createConfig(Request $request){
        $request->isPost() AND $this->saveConfig();
        $this->assign('groups',Config::$groups);
        $this->assign('types',Config::$types);
        return $this->fetch();
    }

    /**
     * 新增 保存
     */
    private function saveConfig(){
        // 表单验证

        $data   =   input('post.');
        // 检测 重复值
        if (!empty($data['form_view']['value']) AND $this->checkUnique($data['form_view']['value'])){
            $this->error('" 表单选项 " 填写的多个选项的值不能有重复！');
        }
        $data['form_view']  =   empty($data['form_view']['value'])?'':serialize($data['form_view']);
       if (Config::create($data,true)){
            $this->success('添加成功！',url('Setting/configLists'));
       }
        $this->error('添加失败！');
    }

    /** 检查 唯一
     * @param $data
     * @return bool
     */
    private function checkUnique($data){
        $tempData = explode("\r\n",$data);
        $temp   =   [];
        foreach ($tempData as $v){
            $tempArr =  explode('|',$v);
            $temp[]    = $tempArr[0];
        }
        return count($temp) != count(array_unique($temp));
    }

    /** 删除 配置
     * @param $config_id
     */
    public function deleteConfig($config_id){
        ($config = Config::get($config_id)) OR $this->error('此配置不存在！');
        if ($config->delete()){
            $this->success('删除成功！',url('Setting/configLists'));
        }
        $this->error('删除失败！');
    }

    /** 配置 排序
     * @param $sort
     */
    public function configSort($sort){
        (!is_array($sort) OR empty($sort)) AND $this->error('没有要排序项！');
        foreach ($sort as $k=>$v){
            Config::update([
                'config_id'  =>  (int)$k,
                'sort'       =>  (int)$v
            ]);
        }
        $this->success('已排序~');
    }

    /** 清除 缓存
     * @return mixed
     */
    public function clear(){
        // runtime/cache
        // runtime/temp
        $result['temp'] = delDirAndFile(TEMP_PATH,true);
        $result['cache'] = delDirAndFile(CACHE_PATH,true);
        $this->assign('result',$result);
        return $this->fetch();
    }

    /** 后台菜单列表
     * @return mixed
     */
    public function admin_nav(){
        $ruleList   =   Category::toLevelTree(AdminNav::all(),0,'admin_nav_id');
        $this->assign('navList',$ruleList);
        return $this->fetch();
    }

    /** 新增 菜单
     * @param Request $request
     * @return mixed
     */
    public function createNav(Request $request,$admin_nav_id = NULL){
        if (!is_null($admin_nav_id)){
            AdminNav::get($admin_nav_id) OR $this->error('不存在此菜单！');
        }
        $request->isPost() AND $this->createNavSave();
        $navList   =   Category::toLevelTree(AdminNav::all(),0,'admin_nav_id');
        $this->assign('navList',$navList);
        $this->assign('admin_nav_id',is_null($admin_nav_id)?0:$admin_nav_id);
        return $this->fetch();
    }


    /**
     * 新增菜单 之 保存
     */
    private function createNavSave(){
        //表单验证
        $data   =   input('post.');
        //检查 是不是 真实有效的 控制器方法
        AuthRule::checkExistence($data['name']) OR $data['name'] == '' OR $data['name'] == '#' OR $this->error('填写的此菜单在系统中不存在！');
        // 如果要求 可以查 唯一
        if (AdminNav::create($data,true)){
            $this->success('增加菜单成功！',url('Setting/admin_nav'));
        }
        $this->error('增加菜单失败！');
    }

    /** 编辑菜单
     * @param Request $request
     * @param $auth_rule_id
     * @return mixed
     */
    public function editNav(Request $request,$admin_nav_id){
        ($admin_nav =    AdminNav::get($admin_nav_id)) OR $this->error('无此菜单,无法编辑！');
        $request->isPost() AND $this->updateNav($admin_nav);
        $navList   =   Category::toLevelTree(AdminNav::all(),0,'admin_nav_id');
        $this->assign('navList',$navList);
        $this->assign('admin_nav',$admin_nav);
        $this->assign('childId',Category::getChildsId($navList,$admin_nav_id,true,'admin_nav_id'));
        return $this->fetch();
    }

    /** 编辑菜单 之  保存
     * @param $auth_rule
     */
    private function updateNav($admin_nav){
        //表单验证
        $data   =   input('post.');
        //检查 是不是 真实有效的 控制器方法
        AuthRule::checkExistence($data['name']) OR $data['name'] == '' OR $data['name'] == '#' OR $this->error('填写的此菜单在系统中不存在！');
        if ($admin_nav->isUpdate()->allowField(true)->save($data)){
            $this->success('更新成功！',url('Setting/admin_nav'));
        }
        $this->error('更新失败！');
    }

    /** 删除菜单  包含 所有子菜单的
     * @param $auth_rule_id
     */
    public function deleteNav($admin_nav_id){
        $rule = AdminNav::all();
        $childId  = Category::getChildsId($rule,$admin_nav_id,true,'admin_nav_id');
        if (AdminNav::destroy($childId)){
            $this->success('删除成功！',url('admin_nav'));
        }
        $this->error('删除失败！');

    }


}